package com.zi.experttalk.experttalk.View;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.zi.experttalk.experttalk.Model.entity.Merchant;
import com.zi.experttalk.experttalk.Model.service.AlterDialogManager;
import com.zi.experttalk.experttalk.Model.service.HttpManager;
import com.zi.experttalk.experttalk.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lenovo on 2014/12/10.
 */
public class CouponActivity extends Activity {
   List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();
   List<Merchant> merchantList=new ArrayList<Merchant>();
   private ListView coupon_shopsItem_listview;
   private Button coupon_tradingArea_bt;
   private Button coupon_categories_bt;
   private Button coupon_defaultSort_bt;
   private  List<String> tradinglist;
   private  List<String> catagoriesList;
   private  List<String> defaultSortList;
    List<Map<String,String>> tradingMapList;
    List<Map<String,String>> catagoriesMapList;
   private String city;
   private String tradingId;
   private String catagoriesId;
   private String defaultSortId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.coupon);
        final ProgressDialog progressDialog=new ProgressDialog(this);
        progressDialog.setMessage("正在加载数据......");
        progressDialog.show();
       //取键
        coupon_shopsItem_listview =(ListView)findViewById(R.id.coupon_shopsItem_listview);
        coupon_tradingArea_bt=(Button) findViewById(R.id.coupon_tradingArea_bt);
        coupon_categories_bt=(Button) findViewById(R.id.coupon_categories_bt);
        coupon_defaultSort_bt=(Button) findViewById(R.id.coupon_defaultSort_bt);

        //获取分类数据
        String initParams="{\"act\":\"init\"}";
        HttpManager httpManager=new HttpManager();
        try {
            httpManager.getHttpInfo(initParams,new HttpManager.GetDataResultListener() {
                @Override
                public void onResult(String data) {
                    Log.d("initdata",data);
                    try {
                        getInitArea(data);
                        progressDialog.dismiss();
                    } catch (JSONException e) {
                        Toast.makeText(CouponActivity.this, "解析有误", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } catch (IOException e) {
            Toast.makeText(this, "网络请求失败", Toast.LENGTH_SHORT).show();
        }
        final AlterDialogManager alterDialog=new AlterDialogManager();
        //商圈点击事件
        coupon_tradingArea_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if(tradinglist.size()!=0){
                        alterDialog.setAlterDialog(CouponActivity.this,tradinglist,coupon_tradingArea_bt,new AlterDialogManager.GetSelecterListener() {
                            @Override
                            public void onResultListener(String selecterItem) {
                                getTradingRefresh(selecterItem);
                            }
                        });
                    }
            }
        });

       //分类点击事件
        coupon_categories_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(catagoriesList.size()!=0){
                    alterDialog.setAlterDialog(CouponActivity.this,catagoriesList,coupon_categories_bt,new AlterDialogManager.GetSelecterListener() {
                        @Override
                        public void onResultListener(String selecterItem) {
                               getCatagoriesRefresh(selecterItem);
                        }
                    });
                }
            }
        });


        //排序点击事件
        coupon_defaultSort_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(defaultSortList.size()!=0){
                    alterDialog.setAlterDialog(CouponActivity.this,defaultSortList,coupon_defaultSort_bt,new AlterDialogManager.GetSelecterListener() {
                        @Override
                        public void onResultListener(String selecterItem) {
                             getDefaultSortRefresh(selecterItem);
                        }
                    });
                }
            }
        });
    /*
    优惠商户列表
     */
        city="1";
        String couponListParam="{\"city_id\":\""+city+"\",\"pwd\":\"\",\"sort\":\"0\",\"page\":\"1\",\"email\":\"\",\"cate_id\":\"0\",\"m_longitude\":\"108.90913391113281\",\"m_latitude\":\"34.237911224365234\",\"quan_id\":\"0\",\"act\":\"youhuilist\",\"key\":\"\"}";
        //获取数据并JSON解析
        getListJsonData(couponListParam);
       /*
       点击商户，进入优惠详情列表
        */
        coupon_shopsItem_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 Map map=new HashMap<String, Object>();
                 map=mapList.get(position);
                 todetails(map);
            }
        });
    }

     /*
     选择类别后刷新
      */
    //商圈刷新
    private void getTradingRefresh(String selecterItem){
        for (int i = 0; i <tradingMapList.size() ; i++) {
            if(selecterItem.equals("全部商圈")){
                tradingId="0";
            }
           else if(selecterItem.equals(tradingMapList.get(i).get("name"))){
                    tradingId=tradingMapList.get(i).get("id");
                  Log.d("trad",tradingId);
              }
        }
      String  newTradingParam="{\"city_id\":\""+city+"\",\"pwd\":\"\",\"sort\":\"0\",\"page\":\"1\",\"email\":\"\",\"cate_id\":\"0\",\"m_longitude\":\"108.90913391113281\",\"m_latitude\":\"34.237911224365234\",\"quan_id\":\""+tradingId+"\",\"act\":\"youhuilist\",\"key\":\"\"}";
      getListJsonData(newTradingParam);
    }
    //分类刷新
    private void getCatagoriesRefresh(String selecterItem){
        for (int i = 0; i <catagoriesMapList.size() ; i++) {
            if(selecterItem.equals("全部分类")){
                catagoriesId="0";
            }
            else if(selecterItem.equals(catagoriesMapList.get(i).get("name"))){
                catagoriesId=catagoriesMapList.get(i).get("id");
                Log.d("cata",catagoriesId);
            }
        }
        String  newCatagoriesParam="{\"city_id\":\""+city+"\",\"pwd\":\"\",\"sort\":\"0\",\"page\":\"1\",\"email\":\"\",\"cate_id\":\""+catagoriesId+"\",\"m_longitude\":\"108.90913391113281\",\"m_latitude\":\"34.237911224365234\",\""+tradingId+"\":\"0\",\"act\":\"youhuilist\",\"key\":\"\"}";
        getListJsonData(newCatagoriesParam);
    }
    //排序刷新
    private void getDefaultSortRefresh(String selecterItem){
        if(selecterItem.equals("默认排序")){
             defaultSortId="0";
        }
        else if(selecterItem.equals("最新")){
            defaultSortId="2";
        }
        else if(selecterItem.equals("最热")){
            defaultSortId="2";
        }
        else if(selecterItem.equals("打印数")){
            defaultSortId="2";
        }
        String  newDefaultSortParam="{\"city_id\":\""+city+"\",\"pwd\":\"\",\"sort\":\""+defaultSortId+"\",\"page\":\"1\",\"email\":\"\",\"cate_id\":\""+catagoriesId+"\",\"m_longitude\":\"108.90913391113281\",\"m_latitude\":\"34.237911224365234\",\""+tradingId+"\":\"0\",\"act\":\"youhuilist\",\"key\":\"\"}";
        getListJsonData(newDefaultSortParam);
    }

    //各类数据显示
    private void  getInitArea(String Data) throws JSONException {
        tradinglist=new ArrayList<String>();
        catagoriesList=new ArrayList<String>();
        defaultSortList=new ArrayList<String>();
        tradingMapList=new ArrayList<Map<String, String>>();
        catagoriesMapList=new ArrayList<Map<String, String>>();


        JSONObject initObject=new JSONObject(Data);
       //商圈数据
        JSONArray  tradingArray=initObject.optJSONArray("quanlist");
        tradinglist.add("全部商圈");
        for (int i = 0; i <tradingArray.length() ; i++) {
              JSONObject itemObiect=tradingArray.optJSONObject(i);
              String name= itemObiect.getString("name");
              String id= itemObiect.getString("id");
              tradinglist.add(name);
              Map<String,String> map=new HashMap<String, String>();
              map.put("name",name);
              map.put("id",id);
              tradingMapList.add(map);
        }
        //分类数据
        JSONArray  catagoriesArray=initObject.optJSONArray("cataloglist");
        catagoriesList.add("全部分类");
        for (int j = 0; j <catagoriesArray.length() ; j++) {
              JSONObject itemObiect=catagoriesArray.optJSONObject(j);
              String name= itemObiect.getString("name");
              String id= itemObiect.getString("id");
              catagoriesList.add(name);
              Map<String,String> map=new HashMap<String, String>();
              map.put("name",name);
              map.put("id",id);
              catagoriesMapList.add(map);
        }
        //默认顺序数据
        defaultSortList.add("默认排序");
        defaultSortList.add("最新");
        defaultSortList.add("最热");
        defaultSortList.add("打印数");

    }

    //获取列表Json数据
     private void  getListJsonData(String requestParam){
         HttpManager httpManager=new HttpManager();
         try {
             httpManager.getHttpInfo(requestParam,new HttpManager.GetDataResultListener() {
                 @Override
                 public void onResult(String data) {
                     if(data!=null){
                         Log.d("data",data);
                         try {
                             addListData(data);
                         } catch (JSONException e) {
                             Toast.makeText(CouponActivity.this,"解析有误",Toast.LENGTH_SHORT).show();
                         }
                     }
                 }
             });
         }catch (IOException e) {
             Toast.makeText(this,"网络请求失败",Toast.LENGTH_SHORT).show();
         }
    }
    //向优惠列表添加数据
    private void addListData(String getedData) throws JSONException {
        merchantList=new ArrayList<Merchant>();
        mapList=new ArrayList<Map<String, Object>>();
        //Json解析
        JSONObject jsonObject=new JSONObject(getedData);
        JSONArray listArray=jsonObject.optJSONArray("item");
        for (int i = 0; i <listArray.length() ; i++) {
            JSONObject itemObject=listArray.optJSONObject(i);
            String id=itemObject.getString("id");
            String title=itemObject.getString("title");
            String logo=itemObject.getString("logo");
            String merchant_logo=itemObject.getString("merchant_logo");
            String address=itemObject.getString("address");
            Merchant merchant=new Merchant();
            merchant.setId(id);
            merchant.setTitle(title);
            merchant.setLogo(logo);
            merchant.setMerchant_logo(merchant_logo);
            merchant.setAddress(address);
            merchantList.add(merchant);
    }
        //数据写入Adapter
        for (int j = 0; j <merchantList.size() ; j++) {
            Map<String,Object> map=new HashMap<String, Object>();
            Merchant merchant=merchantList.get(j);
            map.put("name",merchant.getTitle());
            map.put("address",merchant.getAddress());
            map.put("id",merchant.getId());
            mapList.add(map);
        }
        final SimpleAdapter simpleAdapter=new SimpleAdapter(this,mapList,
                R.layout.coupon_merchant_item,
                new String[]{"name","address"},
                new int[]{R.id.coupon_mItem_mName_textview,R.id.coupon_mItem_mAddress_textview});
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                coupon_shopsItem_listview.setAdapter(simpleAdapter);
            }
        });
    }
    //跳转到详情列表
    private void todetails(Map map){
        Intent intent=new Intent(CouponActivity.this,CouponDetailsActivity.class);
        intent.putExtra("mName",(String)map.get("name"));
        intent.putExtra("mAddress",(String)map.get("address"));
        intent.putExtra("mId",(String)map.get("id"));
        startActivity(intent);
    }
}
